package com.stars.home.vmodel

import android.app.Activity
import android.app.Application
import android.text.Editable
import android.text.TextUtils
import android.util.Log
import androidx.databinding.Bindable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.stars.home.BR
import com.stars.home.utils.net.NetEngine
import com.stars.home.view.SimpleTextWatcher
import com.trailer.base.base.BRepository
import com.trailer.base.base.BViewModel
import kotlinx.coroutines.launch
import java.util.ArrayList

class OpinionVModel(application: Application) : BViewModel<BRepository>(application) {

    val num = 100
    var wordNum = 0

    var textNums: MutableLiveData<String> = MutableLiveData("0/100")

    var fk_id = "0"//0添加

    var categoryBean=MutableLiveData<List<String>>()

    var choseTypeName:String?=null
    //图片
    var type=MutableLiveData<String>()
    var nopath: ArrayList<String> = ArrayList() //全路径


    @Bindable
    var content: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.content)
        }


    fun toSubmit() {

        if(null==choseTypeName){
            toast("请选择问题类别")
            return
        }

        if (TextUtils.isEmpty(content)) {
            toast("请输入意见")
            return
        }

        if(nopath.size==0){
            toast("请输入上传问题的截图或图片")
            return
        }

        var img=""
        for(item in nopath){
            img = if (img == ""){
                item
            }else{
                "$img,$item"
            }
        }

        viewModelScope.launch {
            val resp = repository().lreq { NetEngine.service.feedbackAdd( choseTypeName,content,img) }
            if (resp.ok(true)) {
                var con = repository().context as Activity
                con.finish()
            }
        }

    }

    var text = object : SimpleTextWatcher() {

        override fun afterTextChanged(s: Editable?) {
            super.afterTextChanged(s)
            Log.e("-shy-", "s=: " + s.toString())

            val number = s!!.length
            textNums.value = "$number/$num"
            if (wordNum > num) {
                s.delete(254, wordNum)
                content = s.toString()
                toast("字数超出范围了")
            }

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            super.onTextChanged(s, start, before, count)
            wordNum = s!!.length //实时记录输入的字数

        }
    }


    fun getCategory(){
        viewModelScope.launch{
            var it=repository().lreq { NetEngine.service.category() }
            if(it.ok()){
                categoryBean.value=it.data
            }
        }
    }

    fun choseMoreImg(){
        //选择图片
        type.value="1"
    }
    fun clearMoreImg(position: Int) {
        nopath.removeAt(position)

    }



}
